package controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.log.Log;
import com.jfinal.log.Log4jLog;
import com.jfinal.render.JsonRender;
import config.Constant;
import config.MaopuConfig;
import model.Draw;
import model.Prize;
import model.User;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import util.HttpRequest;
import util.HttpsRequest;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wp1988 on 2016/8/15 0015.
 */
public class MainController extends Controller {

    public void index() {
        System.out.println("enter index");
        render("index.html");
    }

    public void reg() {
        System.out.println("enter reg");
        render("register.html");
    }

    /**
     * 请求验证码
     */
    public void requestCode() {
        System.out.println("requestCode");

        JSONObject result = new JSONObject();

        //接收参数
        String phone = getPara("phone");

        //构造发送验证码参数
        StringBuilder builder = new StringBuilder();
        builder.append("appkey=").append(Constant.MOB_APP_KEY).append("&")
                .append("phone=").append(phone.trim()).append("&")
                .append("zone=86");

        // 发送验证码，获取返回结果
        String sendCodeResponse = null;
        try {
            sendCodeResponse = HttpsRequest.sendGet(Constant.MOB_SMS_SEND_CODE_URL, builder.toString());
        } catch (Exception e) {
            sendCodeResponse = null;
        }

        // 处理返回结果
        if (sendCodeResponse == null) {
            // 发送失败
            result.put("code", -1);
            result.put("msg", "验证码请求失败");
        } else {
            // 解析返回数据
            JSONObject obj = new JSONObject(sendCodeResponse);
            if (obj.has("status") && obj.getInt("status") == 200) {
                result.put("code", 0);
            } else {
                result.put("code", -1);
                result.put("msg", "验证码请求失败");
            }
        }

        //返回数据
        renderText(result.toString());

    }

    /**
     * 注册
     */
    public void register() {
        JSONObject result = new JSONObject();

        //接收参数
        String name = getPara("name");
        String phone = getPara("phone");
        String code = getPara("code");
        String address = getPara("address");
        String province = getPara("province");
        String city = getPara("city");
        String county = getPara("county");

        //校验验证码
        if (checkCode(phone, code)) {
            System.out.println(phone + " 验证成功");
            //检查该手机号是否已注册
            List<User> users = User.dao.find("select * from user where phone='" + phone + "'");
            if (users == null || users.size() == 0) {
                //未注册
                System.out.print(phone + " 未注册");
                //保存到数据库
                new User().set("user_name", name)
                        .set("phone", phone)
                        .set("province", province)
                        .set("city", city)
                        .set("county", county)
                        .set("address", address)
                        .set("regis_date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                        .save();
                System.out.println(phone + " 注册成功");
                //返回0，表示注册成功
                result.put("code", 0);

            } else {
                //已注册
                System.out.print(phone + " 已注册");
                //返回1，表示已注册
                result.put("code", 1);
            }

        } else {
            System.out.println(phone + " 验证失败");
            //返回-1 表示校验验证码失败
            result.put("code", -1);
        }

        //返回数据
        renderText(result.toString());

    }

    /**
     * 抽奖
     */
    public void draw() {
        JSONObject result = new JSONObject();
        //接收参数
        String phone = getPara("phone");
        System.out.println(phone+"准备抽奖");
        //获取用户ID
        List<User> users = User.dao.find("select * from user where phone='" + phone + "'");
        if(users != null && users.size()>0){
            User user = users.get(0);
            String userId = user.getLong("user_id").toString();
            System.out.println("该用户的ID为："+userId);
            //检查该手机号是否已抽中奖
            List<Draw> draws = Draw.dao.find("select * from draw where user_id=" + userId +" and draw_result = '0'");
            if (draws == null || draws.size() == 0) {
                //未抽中
                System.out.println("该用户未抽中过奖");
                //检查该用户今天是否已抽过奖
                //获取今天的日期
                String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                System.out.println("今天日期为："+today);
                draws = Draw.dao.find("select * from draw where user_id=" + userId +" and draw_date like '"+today+"%'");
                if (draws == null || draws.size() == 0){
                    //今天未抽过奖
                    //检查该用户所在地区今天还有无剩余奖品
                    //获取用户所在地区
                    String areaCode = user.getStr("county");
                    String sql = "select * from prize where area_code ='"+areaCode+"' and date = '"+today+"'";
                    System.out.println("检查该用户所在地区今天还有无剩余奖品 sql:"+sql);
                    List<Prize> prizes = Prize.dao.find(sql);
                    if(prizes != null && prizes.size()>0){
                        Prize prize = prizes.get(0);
                        long count = prize.getLong("count");//总数
                        long remain = prize.getLong("remain");//剩余
                        System.out.println("总数为："+count+"  剩余奖品数为："+remain);
                        if(remain > 0){
                            //还有剩余
                            System.out.println("该地区还有剩余名额");
                            result.put("code", 0);
                        }else{
                            //今日无剩余名额
                            System.out.println("该地区今天无剩余名额");
                            result.put("code", 1);
                        }
                    } else{
                        //该地区没有名额，用户不可以抽奖（或者说只可以抽谢谢参与）
                        System.out.println("该地区没有名额");
                        result.put("code", 2);
                    }
                }else{
                    //今天已抽过奖
                    result.put("code", 3);
                }
            } else {
                //已抽中
                System.out.println("该用户已抽中过奖");
                result.put("code", 4);
            }
        }

        //返回数据
        renderText(result.toString());

    }

    /**
     * 通知服务器抽奖结果，保存到数据库
     */
    public void drawOver(){
        JSONObject result = new JSONObject();
        //接收参数
        String phone = getPara("phone");
        String code = getPara("code");
        System.out.println(phone+"的抽奖结果为"+code);
        //获取用户ID
        List<User> users = User.dao.find("select * from user where phone='" + phone + "'");
        if(users != null && users.size()>0){
            User user = users.get(0);

            //更新剩余奖品数目
            if(code.equals("0")){
                String areaCode = user.getStr("county");
                String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                String sql = "select * from prize where area_code ='"+areaCode+"' and date = '"+today+"'";
                List<Prize> prizes = Prize.dao.find(sql);
                if(prizes != null && prizes.size()>0){
                    Prize prize = prizes.get(0);
                    long id = prize.getLong("id");
                    System.out.println("prize ID为: "+id);
                    long temp =  prize.getLong("remain");
                    System.out.println(id+"的剩余奖品数目为"+temp);
                    if(temp > 0){
                        //保存到数据库中
                        new Draw().set("user_id", user.getLong("user_id"))
                                .set("draw_date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                                .set("draw_result", code)
                                .save();
                        //更新prize 剩余数目

                        Prize.dao.findById(id).set("remain", temp -1).update();
                        result.put("code", 0);
                    }else{
                        result.put("code", -1);
                    }
                }

            }else if(code.equals("1")){
                System.out.println(phone+"此次不能中奖");
                result.put("code", 0);
            }else{
                result.put("code", -1);
            }

        }else {
            result.put("code", -1);
        }

        //返回数据
        renderText(result.toString());
    }

    /**
     * 校验 验证码
     *
     * @param phone
     * @param code
     * @return
     */
    private boolean checkCode(String phone, String code) {
        // 构造验证参数
        StringBuilder builder = new StringBuilder();
        builder.append("appkey=").append(Constant.MOB_APP_KEY).append("&")
                .append("phone=").append(phone.trim()).append("&")
                .append("code=").append(code.trim()).append("&")
                .append("zone=86");
        // 验证验证码，获取返回结果
        String checkCodeResponse = null;
        try {
            checkCodeResponse = HttpsRequest.sendGet(Constant.MOB_SMS_CHECK_CODE_URL, builder.toString());
        } catch (Exception e) {
            checkCodeResponse = null;
        }

        // 处理返回结果
        if (checkCodeResponse == null) {
            return false;
        } else {
            // 解析返回数据
            JSONObject obj = new JSONObject(checkCodeResponse);
            if (obj.has("status") && obj.getInt("status") == 200) {
                // 尝试注册
                // 获取归属地
                /*String getBelongResponse = null;
                String belong = "";
                try{
                    getBelongResponse = HttpRequest.sendGet(Constant.GET_BELONG_URL, "chgmobile="+phone.trim());
                }catch(Exception e){
                    getBelongResponse = null;
                    e.printStackTrace();
                }
                if(getBelongResponse != null)
                    belong = parseBelongInfo(getBelongResponse.toString());
                else
                    belong = "未知";*/
                return true;
            } else {
                return false;//todo 测试用，记得改回false
            }

        }
    }

    private String parseBelongInfo(String data) {
        String result = "";
        try {
            StringReader sr = new StringReader(data);
            InputSource is = new InputSource(sr);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            String province = doc.getElementsByTagName("province").item(0).getTextContent();
            String city = doc.getElementsByTagName("city").item(0).getTextContent();
            System.out.println("province = " + province);
            System.out.println("city = " + city);
            result = province + " " + city;
        } catch (Exception e) {
            result = "未知";
        }

        return result;
    }

}
